<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意:只允许为第三级分类设置相关参数 "
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectKeys"
            :options="catList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many" :disabled="isBtnVisible">
          <el-button type="primary" size="mini" @click="addParamsDialogVisible"
            >添加参数</el-button
          >
          <el-table :data="manyParamsList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleTagClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsDialogVisible(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only" :disabled="isBtnVisible">
          <el-button type="primary" size="mini" @click="addParamsDialogVisible"
            >添加属性</el-button
          >
          <el-table :data="onlyParamsList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleTagClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsDialogVisible(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数和静态属性对话框 -->
    <el-dialog
      :title="titleChange"
      :visible.sync="DialogVisible"
      width="50%"
      @close="addParamsDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="60px"
      >
        <el-form-item label="添加" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsRequest">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改的对话框 -->
    <el-dialog
      title="修改参数"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="60px"
      >
        <el-form-item label="添加" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogRequest">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类数据源
      catList: [],
      //   级联选择框的数据对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //   级联选择框选中的value值
      selectKeys: [],
      // 被激活的标签页名称
      activeName: 'many',
      // 动态参数列表
      manyParamsList: [],
      // 静态属性列表
      onlyParamsList: [],
      // 隐藏添加属性对话框
      DialogVisible: false,
      // 添加参数表单数据
      addParamsForm: {
        attr_name: '',
      },
      addParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }],
      },
      editDialogVisible: false,
      editParamsForm: {
        attr_name: '',
        attr_id: 0,
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入新的属性名', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCatList()
  },
  computed: {
    // 控制页签是否禁用
    isBtnVisible() {
      if (this.selectKeys.length != 3) {
        return true
      }
      return false
    },
    // 获取第三级分类的id，用于发起网络请求
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    //添加对话框标题的计算属性
    titleChange() {
      if (this.activeName === 'many') {
        return '添加动态参数'
      } else {
        return '添加静态属性'
      }
    },
  },
  methods: {
    //   获取分类数据
    async getCatList() {
      const { data: res } = await this.axios.get('categories')
      //   console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.catList = res.data
    },
    // 级联选择框选中值变化时，会触发这个函数
    handleChange() {
      this.manyParamsList = []
      this.onlyParamsList = []
      this.getParamsData()
      // console.log(this.selectKeys)
    },
    // 当点击页签触发的事件
    handleTabClick() {
      this.getParamsData()
      console.log(this.activeName)
    },

    // 发起网络请求，获取分类参数
    async getParamsData() {
      if (this.selectKeys.length <= 2) {
        this.selectKeys = []
        return this.$message.error('只允许选择三级分类')
      }
      const { data: res } = await this.axios.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status != 200) {
        return this.$message.error('获取分类参数失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyParamsList = res.data
      } else {
        this.onlyParamsList = res.data
      }

      console.log(res)
    },
    // 控制添加参数对话框的显示
    addParamsDialogVisible() {
      this.DialogVisible = true
    },
    // 对添加表单进行重置
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 发起网络请求,添加动态参数和静态属性
    addParamsRequest() {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('添加失败')
        }
        const { data: res } = await this.axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.DialogVisible = false
        this.getParamsData()
        console.log(res)
      })
    },
    // 点击修改按钮显示对话框
    editParamsDialogVisible(params) {
      this.editParamsForm.attr_name = params.attr_name
      this.editParamsForm.attr_id = params.attr_id
      this.editDialogVisible = true
    },
    // 对修改的表单进行重置
    editDialogClosed() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 发起网络请求，修改动态参数和静态属性
    editDialogRequest() {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('修改失败')
        }
        const { data: res } = await this.axios.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    deleteParams(id) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.axios.delete(
            `categories/${this.cateId}/attributes/${id}`
          )
          if (res.meta.status != 200) {
            return this.$message.error('删除失败')
          }
          this.getParamsData()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    showInput(data) {
      data.inputVisible = true
      // 让文本框获得焦点
      // $nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会执行回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去焦点或按下enter键都会触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //  如果没有return，则说明输入了内容，需要做后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      const { data: res } = await this.axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status != 200) {
        return this.$message.error('操作失败')
      }
      this.$message.success('操作成功')
    },
    handleTagClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
  },
}
</script>

<style>
.cat_opt {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.input-new-tag {
  width: 120px !important;
}
</style>
